import moment from "moment";
import {Tag, Tooltip} from "antd";
import XLSX from 'xlsx';



const columsMap = {
    'id':  'id',
    'title': '标题',
    'author': '作者',
    'amount': '阅读量',
    'createAt': '创建时间'
}
//处理时间戳
function dateFormat(date) {
    return moment(date).format('YYYY年MM月DD日 HH:mm:ss')
}

function createColumns(columnsKeys) {
    let columns = [];
    columns = columnsKeys.map(item => {
        if(item === 'amount')
        {
            return {
                title:  columsMap[item],
                // dataIndex: item,
                key: item,
                render: (text,record) => {
                    // console.log(text,index,record);
                    return  (
                        <Tooltip title={record.amount>1000 ? "多于1000" : "少于1000"}>
                            <Tag color={record.amount>1000 ? "red" : "green"}>
                                {record.amount}
                            </Tag>
                        </Tooltip>
                    )
                }
            }
        }else if (item === 'createAt')
        {
            return {
                title:  columsMap[item],
                // dataIndex: item,
                key: item,
                render: (text,record) => {
                    // console.log(text,index,record);
                    return dateFormat(record.createAt);
                }
            }
        }
        return {
            title:  columsMap[item],
            dataIndex: item,
            key: item,
        }

    })

    return columns;
}


//将数据处理为导出excel时想要的二维数组形式
function  handleData(list){
    //数组的第一行数据是表头，第二行数据是，数据

    let DataList = [];
    const firstLine = Object.values(columsMap);
    DataList.push(firstLine);
   /*
   * [{id: "540000198208215206", title: "儿济年党厂位对又构火头", author: "郭秀兰", amount: 1388, createAt: 1502391902079}
    {id: "130000197712142666", title: "提中号线划设越向手王所", author: "丁超", amount: 1458, createAt: 1146301549502}]
    * 列表里面的每个元素都是对象，将对象转换为数组即可
   * */
    const listItems = list.map(item => {
        item.createAt = moment(item.createAt).format('YYYY-MM-DD HH:mm:ss')
        const listItem = Object.values(item);
        return listItem;
    })

    DataList.push(...listItems);

    return DataList;

}

//导出excel表格的函数
function exportExcel(list) {
    //data是一个二维数组
    const data = handleData(list);
    console.log(data);
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb,ws ,"SheetJS");
    XLSX.writeFile(wb, `article-${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`);

}
export {
    createColumns,
    exportExcel,
    dateFormat
}